package com.kang.commons.util;

import com.kang.commons.exception.ParamException;
import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class ValidationUtil {

    private static final Validator VALIDATOR;
    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        VALIDATOR = factory.getValidator();
    }

    public static void validate(Object object) {
        Set<ConstraintViolation<Object>> violations = VALIDATOR.validate(object);
        if(CollectionUtils.isNotEmpty(violations)) {
            StringBuffer msgBuf = new StringBuffer();
            violations.forEach(violation -> msgBuf.append(violation.getMessage()).append("；"));

            throw new ParamException(msgBuf.toString());
        }
    }


}
